package com.example.design.ordermanagement.Listener;

import com.example.design.ordermanagement.command.OrderCommand;
import com.example.design.ordermanagement.command.invoker.OrderCommandInvoker;
import com.example.design.ordermanagement.state.OrderState;
import com.example.design.ordermanagement.state.OrderStateChangeAction;
import com.example.design.pojo.Order;
import com.example.design.utils.RedisUtils;

import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.xml.ws.spi.Invoker;

@Component
@WithStateMachine(name = "orderStateMachine")
public class OrderStateListener {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private OrderCommand orderCommand;


    @OnTransition(source = "ORDER_WAIT_PAY",target = "ORDER_WAIT_SEND")
    public boolean payToSend(Message<OrderStateChangeAction> message){
        //从 Redis 获取订单，并判断当前订单状态是否是待支付
        Order order = (Order) message.getHeaders().get("order");
        if (order.getOrderState() != OrderState.ORDER_WAIT_PAY){
            throw new UnsupportedOperationException("订单状态异常");
        }
        //支付成功后修改订单状态为代发货，并更新Redis
        order.setOrderState(OrderState.ORDER_WAIT_SEND);
        redisUtils.set(order.getOrderId(),order);
        //todo 使用命令模式进行相关处理
        OrderCommandInvoker invoker = new OrderCommandInvoker();
        invoker.invoke(orderCommand,order);
        return true;
    }

    @OnTransition(source = "ORDER_WAIT_SEND",target = "ORDER_WAIT_RECEIVE")
    public boolean sendToReceive(Message<OrderStateChangeAction> message){
        Order order = (Order) message.getHeaders().get("order");
        if (order.getOrderState() != OrderState.ORDER_WAIT_SEND){
            throw new UnsupportedOperationException("订单状态异常");
        }
        order.setOrderState(OrderState.ORDER_WAIT_RECEIVE);
        redisUtils.set(order.getOrderId(),order);
        //todo 使用命令模式进行相关处理
        OrderCommandInvoker invoker = new OrderCommandInvoker();
        invoker.invoke(orderCommand,order);
        return true;
    }

    @OnTransition(source = "ORDER_WAIT_RECEIVE",target = "ORDER_FINISH")
    public boolean receiveToFinish(Message<OrderStateChangeAction> message){
        Order order = (Order) message.getHeaders().get("order");
        if (order.getOrderState() != OrderState.ORDER_WAIT_RECEIVE){
            throw new UnsupportedOperationException("订单状态异常");
        }
        order.setOrderState(OrderState.ORDER_FINISH);
        redisUtils.del(order.getOrderId());
        redisUtils.del(order.getOrderId()+"STATE");
        //todo 使用命令模式进行相关处理
        OrderCommandInvoker invoker = new OrderCommandInvoker();
        invoker.invoke(orderCommand,order);
        return true;
    }


}
